package net.test.piggy.listener;

import com.fasterxml.jackson.core.JsonProcessingException;
import okhttp3.Response;
import okhttp3.sse.EventSource;
import okhttp3.sse.EventSourceListener;
import org.jetbrains.annotations.NotNull;
import org.springframework.lang.Nullable;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.concurrent.CountDownLatch;

public class MyEventSourceListener extends EventSourceListener {

    private final HttpServletResponse response;
    private final CountDownLatch countDownLatch;
    public MyEventSourceListener(HttpServletResponse response,CountDownLatch countDownLatch) {
        this.response = response;
        this.countDownLatch = countDownLatch;
    }

    @Override
    public void onOpen(@NotNull EventSource eventSource, @NotNull Response response) {
        boolean successful = response.isSuccessful();
        System.out.println("EventSourceListener --> onOpen --> "+successful);
    }

    @Override
    public void onEvent(@NotNull EventSource eventSource, @Nullable String id, @Nullable String type, @NotNull String data) {
        try {
            response.getWriter().write(data);
            response.getWriter().flush();
            System.out.println(data);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public void onClosed(@NotNull EventSource eventSource) {
        System.out.println("EventSourceListener --> onClosed");
        countDownLatch.countDown();
    }

    @Override
    public void onFailure(@NotNull EventSource eventSource, @Nullable Throwable t, @Nullable Response response) {
        System.out.println("EventSourceListener --> onFailure");
        countDownLatch.countDown();
    }
}
